package com.css.dzj.zfjg.modules.jcdx.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.css.dzj.zfjg.common.exception.CvaException;
import com.css.dzj.zfjg.modules.jcdx.entity.JgLhjgJcdxEntity;
import com.css.dzj.zfjg.modules.jcdx.entity.QJgLhjgJcdxEntity;
import com.css.dzj.zfjg.modules.jcdx.mapper.JgLhjgJcdxMapper;
import com.css.dzj.zfjg.modules.jcdx.service.JgLhjgJcdxService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JgLhjgJcdxServiceImpl implements JgLhjgJcdxService {
    @Autowired
    private JgLhjgJcdxMapper jcdxMapper;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Override
    public QueryResults<JgLhjgJcdxEntity> queryPage(String objectname, Pageable pageable) {
        QJgLhjgJcdxEntity q = QJgLhjgJcdxEntity.jgLhjgJcdxEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        /**
         * 查询条件
         */
        predicate = (StringUtils.isEmpty(objectname)) ? predicate : ExpressionUtils.and(predicate, q.objectname.like("%" + objectname + "%"));

        // 返回结果
        return jpaQueryFactory.selectFrom(q).where(predicate)
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
    }

    @Override
    public JgLhjgJcdxEntity getById(String taskno) {
        QJgLhjgJcdxEntity q = QJgLhjgJcdxEntity.jgLhjgJcdxEntity;
        return jpaQueryFactory.selectFrom(q).where(q.taskno.eq(taskno)).fetchOne();
    }

    @Override
    public void save(JgLhjgJcdxEntity jcdxEntity) {
        if (jcdxEntity == null){
            throw new RuntimeException("实体为空");
        }
        jcdxMapper.save(jcdxEntity);
    }

    @Override
    public void updateById(JgLhjgJcdxEntity jcdxEntity) {
        if (jcdxEntity == null){
            throw new RuntimeException("实体为空");
        }
        // 实体中必须有ID
        jcdxMapper.save(jcdxEntity);
    }

    @Override
    public void updateJcdx(JgLhjgJcdxEntity jcdxEntity) throws CvaException {
        updateById(jcdxEntity);
    }
}
